package v1

import (
	"fmt"
	model2 "gin_vue_blog/model"
	"gin_vue_blog/utils/errmsg"
	"gin_vue_blog/utils/validator"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 添加分类
func AddCategory(c *gin.Context) {
	var data model2.Category
	_ = c.ShouldBindJSON(&data)
	msg, code := validator.Validator(data)
	if code != errmsg.SUCCESS {
		c.JSON(200, gin.H{
			"status": code,
			"msg":    msg,
		})
		return
	}
	code = model2.CheckUserExist(data.Name)
	if code == errmsg.ERROR_USER_NOT_EXIST {
		model2.AddCate(&data)
		code = errmsg.SUCCESS
	}
	c.JSON(200, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 查询单个分类
func GetCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	fmt.Println("id=", id)
	data, code := model2.GetCateInfo(id)
	c.JSON(200, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 查询分类列表
func GetCategoryList(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageNum == 0 {
		pageNum = 1
	}
	data, code := model2.GetCateList(pageSize, pageNum)
	c.JSON(200, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 更新分类
func EditCategory(c *gin.Context) {
	var data model2.Category
	id, _ := strconv.Atoi(c.Param("id"))
	_ = c.ShouldBindJSON(&data)
	code := model2.CheckUpCate(id, data.Name)
	if code == errmsg.SUCCESS {
		model2.EditCate(id, &data)
	}
	c.JSON(200, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 删除分类
func DeleteCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model2.DeleteCate(id)
	c.JSON(200, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}
